<?php
class QueueController extends BaseArticleController {

	protected $layout = 'layouts.master';

	protected $last_msgs = [];

	protected $unread_counts = [];
	
	/**
	 * 备份圈子的聊天记录
	 */
	public function group_chat_backup(){
		// 1. back up the chat records
		try{
			$easemob = new Easemob();
			$messages = [];
			$arr = $easemob->getCursor();
			$timestamp = isset($arr['expires_in'])?$arr['expires_in']:'0';
			$latest_time = SNSMsg::getLatestTimestamp();
			Log::info(__METHOD__ . __LINE__ . " " . $latest_time);
			$cursor='';      		//环信分页参数
			$ql = "ql=select+*+where+timestamp>".$latest_time;
			$last_msgs = [];
			do{
				$result = $easemob->chatRecord($ql, $cursor, $limit=200);
				$result = json_decode($result);
				if (is_object($result)) {
					$messages = $result->entities;
					foreach($messages as $message){
						$msg = SNSMsg::where('msg_id', $message->msg_id)->first();
						if (!$msg) {
							SNSMsg::_storeChat($message);
							$this->updateLastMsgs($message);
							$this->updateUnreadCounts($message);
						} else {
							Log::info(sprintf(__METHOD__ . __LINE__ . " message with msg_id: '%s' already exists in db", $message->msg_id));
						}
					}
				}
				if(isset($result->cursor)){
					$cursor = $result->cursor;
				} else {
					$cursor = '';
				}
				sleep(0.05);  //环信限制每个ip每秒访问次数为30次，此处为防止备份数据时每秒次数超过上限而设置为每秒最多可访问20次
			}while($cursor);
		}catch (Exception $ex){
			Log::error($ex);
			return $this->makeView('errors.503', '请求失败', 503);
		}

		// 2. take the last msg and update the record on the sns group table
		if (count($this->last_msgs)) {
			foreach($this->last_msgs as $associate_id => $content) {
				$group = App::make('SNSGroup')->find($associate_id);
	    		if ($group) {
	    			$group->last_msg = $content;
	    			$group->save();
	    		}
			}
		}

		// 3. calculate how many new msgs are being added, and update the unread count for a group member
		if (count($this->unread_counts)) {
			foreach($this->unread_counts as $associate_id => $count) {
				$members = App::make('SNSGroupMember')->where("group_id", $associate_id)->get();
				foreach($members as $member) {
					$member->unread_count = $member->unread_count + $count;
					$member->save();
					Log::info(__METHOD__ . __LINE__ . " associate_id " . $associate_id . " member " . $member->id);
				}
			}
		}

		return $this->makeView('', $messages, 200);
	}

	/**
	 * 更新圈子的最后一条信息
	 * 
	 * @param $message 从环信得到的message对象
	 */
	protected function updateLastMsgs($message) {
		if ($message->chat_type != 'groupchat') {
			return;
		}

		$associate_id = 0;
		if (isset($message->payload->ext)) {
			if (isset($message->payload->ext->associate_id)) {
				$associate_id = $message->payload->ext->associate_id;
			}
		}

		$msgs = $message->payload->bodies;
		$content = "";
		if($msgs[0]->type == 'txt'){
			$content = $msgs[0]->msg;
		}

		if($associate_id && $content) {
			$this->last_msgs[$associate_id] = $content;
		}
	}

	/**
	 * 更新圈子成员的未读消息数
	 * 
	 * @param $message 从环信得到的message对象
	 */
	protected function updateUnreadCounts($message) {
		if ($message->chat_type != 'groupchat') {
			return;
		}
		
		Log::info(__METHOD__ . __LINE__);
		$associate_id = 0;
		if (isset($message->payload->ext)) {
			if (isset($message->payload->ext->associate_id)) {
				$associate_id = $message->payload->ext->associate_id;
			}
		}

		Log::info(__METHOD__ . __LINE__ . " associate_id " . $associate_id);
		if ($associate_id) {
			if (!isset($this->unread_counts[$associate_id])) {
				$this->unread_counts[$associate_id] = 1;
			} else {
				$this->unread_counts[$associate_id]++;
			}
		}

		Log::info(__METHOD__ . __LINE__ . " var_dump all " . json_encode($this->unread_counts));
	}
	
	/**
	 * 自动确认
	 */
	public function autocomplete()
	{
		// 找到状态在Replied超过24小时的一对一咨询
		$query = Post::select('id', 'creator_id', 'status', 'created_at', 'updated_at')
			->where('status', '=', Post::STATUS_REPLIED)
			->whereIn('type', [Post::TYPE_PAY_TEXT, Post::TYPE_PAY_PHONE, Post::TYPE_PAY_COMPANY])
			->where('updated_at', '<', date("Y-m-d H:i:s", strtotime("-1 day")))
			->orderBy('updated_at', 'DESC');

		// 把他们的状态自动改为
		$posts = $query->get();
		foreach($posts as $post) {
			$post->status = Post::STATUS_WAIT_FOR_EVALUATION;
			$post->save();
		}

		Log::info(__METHOD__ . __LINE__ . " " . sprintf("finished autocompleting %s questions.", count($posts)));
		return $this->makeView('', sprintf("finished autocompleting %s questions.", count($posts)), 200);
	}
}
